package cloud.maque.sms.aliyun;

import cloud.maque.sms.api.dto.SmsDTO;
import cloud.maque.sms.conf.SmsProperties;
import com.alibaba.fastjson2.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import cloud.maque.sms.api.dto.SmsResponse;
import cloud.maque.sms.api.provider.SmsProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AliyunSmsProvider implements SmsProvider {


    @Autowired
    SmsProperties smsProperties;

    @Override
    public SmsResponse send(SmsDTO request) {
        try {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsProperties.getAliyun().getAccessKeyId(), smsProperties.getAliyun().getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            SendSmsRequest aliRequest = new SendSmsRequest();
            aliRequest.setPhoneNumbers(request.getPhoneNumber());
            aliRequest.setSignName(request.getSignName());
            aliRequest.setTemplateCode(request.getTemplateCode());
            aliRequest.setTemplateParam(JSON.toJSONString(request.getTemplateParam()));

            SendSmsResponse response = client.getAcsResponse(aliRequest);

            return SmsResponse.builder().success("OK".equals(response.getCode())).code(response.getCode()).message(response.getMessage()).requestId(response.getRequestId()).build();
        } catch (Exception e) {
            return SmsResponse.builder().success(false).code("ERROR").message(e.getMessage()).build();
        }
    }

    @Override
    public String getProviderName() {
        return "aliyun";
    }
}
